using MediatR;
using MeetingManagement.Application.Common;
using MeetingManagement.Domain.Entities;
using MeetingManagement.Domain.Repositories;

namespace MeetingManagement.Application.Commands.Users.Register;

public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, RegisterUserResult>
{
    private readonly IRepository<User> _userRepository;
    private readonly IPasswordHasher _passwordHasher;

    public RegisterUserCommandHandler(IRepository<User> userRepository, IPasswordHasher passwordHasher)
    {
        _userRepository = userRepository;
        _passwordHasher = passwordHasher;
    }

    public async Task<RegisterUserResult> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
    {
        bool emailExists = _userRepository.Query().Any(u => u.Email == request.Email);
        if (emailExists)
        {
            return new RegisterUserResult
            {
                Success = false,
                Message = "Email already exists"
            };
        }

        var user = User.Create(
            request.Username,
            request.Email,
            _passwordHasher.Hash(request.Password)
        );

        await _userRepository.CreateAsync(user);

        return new RegisterUserResult
        {
            Success = true,
            Message = "User registered successfully",
            User = user
        };
    }
}
